import React, { Component } from 'react';
import { connect } from 'dva';
import { Spin, Button, message, Card, Table, Row, Col, Tooltip, Form, Input, Popconfirm, Modal, Select } from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import { FormattedMessage } from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import systemMenu from "@/pages/settings/menu/systemMenu";

@connect(({ menuButtonsModel, loading }) => ({
  menuButtonsModel
}))
@Form.create()
class menuButtons extends Component {
  state = {
    loading: false,
    pageDataSource: [],
    selectedKeys: [],
    editData: {},
    isShowEditModal: false,
    newestMenuCode: "",
    menuDataSource: []
  };

  componentDidMount() {
    this.findPageDataSource();
    this.findMenus();
    this.setterNewestRoleCode();
  }

  setterNewestRoleCode = () => {
    const { editData } = this.state;
    const editDataLength = Object.keys(editData).length;
    if(editDataLength > 0) return;
    editData.code = APP.getCode("B");
    this.setState({editData});
  }

  findPageDataSource = (e) => {
    let that = this, params = {};
    if(e){
      e.preventDefault();
    }
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      APP.validNilParams(values);
      params = {...params, ...values};
      requestContinue();
    });
    function requestContinue(){
      const { dispatch } = that.props;
      APP.loading(that);
      dispatch({
        type: "menuButtonsModel/moduleList",
        payload: params,
        callback: function(data){
          APP.closeLoading(that);
          if(data.success){
            that.setState({
              pageDataSource: data.datas,
              selectedKeys: []
            });
          }
        }
      });
    }
  }

  findMenus(){
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: "systemMenuModel/fetch",
      callback: function(data) {
        if(data.success){
          that.setState({
            menuDataSource: data.datas
          });
        }
      },
    });
  }

  getDataById = () => {
    const { selectedKeys } = this.state;
    if(selectedKeys.length != 1) return;
    const that = this,
      { dispatch } = that.props,
      id = selectedKeys[0];
    if(!APP.isValidObj(id)) return;
    APP.loading(that);
    dispatch({
      type: "menuButtonsModel/getModuleById",
      payload: {id: id},
      callback: function(data){
        that.setterNewestRoleCode();
        that.setState({
          loading: false,
          editData: data.datas,
          isShowEditModal: true
        });
      }
    });
  }

  enabledControl = (isEnabled) => {
    const { selectedKeys } = this.state;
    if(selectedKeys <= 0) return;
    const that = this, { dispatch } = this.props;
    APP.loading(that);
    dispatch({
      type: "menuButtonsModel/enabledControl",
      payload: {
        ids: selectedKeys.join(","),
        isEnabled: isEnabled
      },
      callback: function(data){
        APP.closeLoading(that);
        if(data.success){
          message.success("操作成功");
          that.findPageDataSource();
        }else{
          message.error("操作失败！");
        }
      }
    });
  }


  render() {
    const {
      loading,
      pageDataSource,
      selectedKeys
    } = this.state;
    const { form } = this.props;
    const that = this;
    const { getFieldDecorator } = form;
    /**
     * 表格选中事件
     * @Author 肖家添
     * @Date 2019/8/19 19:15
     */
    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onChange: selectedRowKeys => {
        that.setState({ selectedKeys: selectedRowKeys });
      },
    };
    /**
     * 按钮样式
     * @Author 肖家添
     * @Date 2019/8/19 19:42
     */
    const buttonsStyle = {
      style: {
        marginRight: '15px',
      },
    };

    return (
      <Spin spinning={loading}>
        <PageHeaderWrapper title={<FormattedMessage id="menu.settings.menuButtons"/>}>
          <Card style={{marginBottom: 15}}>
            <Form layout="inline" onSubmit={this.findPageDataSource}>
              <Row>
                <Col span={8}>
                  <Form.Item label="按钮编号">
                    {getFieldDecorator('code', {})(<Input placeholder="请输入按钮编号"/>)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="按钮名称">
                    {getFieldDecorator('name', {})(<Input placeholder="请输入按钮名称"/>)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="所属菜单">
                    {getFieldDecorator('menuId', {})(
                      <Select placeholder={"请选择所属菜单"} allowClear={true} style={{ width: 174 }}>
                        {this.getMenuOptions()}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}>
                  <Button type="primary" htmlType="submit">
                    查找
                  </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card style={{marginBottom: 15}}>
            <Button type="primary" {...buttonsStyle} onClick={() => {
              this.setterNewestRoleCode();
              this.setState({isShowEditModal: true});
            }}>
              新增
            </Button>
            <Tooltip
              title={selectedKeys.length == 1 ? '' : '请选中一行数据'}
            >
              <Button type="primary" {...buttonsStyle} onClick={() => this.getDataById()}>
                编辑
              </Button>
            </Tooltip>
            <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
              <Button type="primary" {...buttonsStyle} onClick={() => this.enabledControl(1)}>
                上架
              </Button>
            </Tooltip>
            <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
              <Button type="primary" {...buttonsStyle} onClick={() => this.enabledControl(0)}>
                下架
              </Button>
            </Tooltip>
            <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
              <Popconfirm
                title="确定删除选中数据吗？"
                onConfirm={() => this.enabledControl(-1)}
                okText="删除"
                cancelText="取消"
                disabled={!(selectedKeys.length > 0)}
              >
                <Button type="primary" {...buttonsStyle}>
                  删除
                </Button>
              </Popconfirm>
            </Tooltip>
          </Card>
          <Card>
            <Table
              bordered
              rowKey={data => `${data.id}`}
              rowSelection={rowSelection}
              columns={this.columns}
              dataSource={pageDataSource}
              pagination={{
                  showTotal: total => `共 ${total} 条数据`,
              }}
            />
          </Card>
          {this.buildEditModal()}
        </PageHeaderWrapper>
      </Spin>
    );
  }

  /**
   * 构建编辑数据模态框
   * @Author 肖家添
   * @Date 2020/3/8 17:11
   */
  buildEditModal = () => {
    return <EditForm
      parent={this}
    />;
  }

  columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '状态',
      dataIndex: 'isenabled',
      render: function(text) {
        if (text == '1' || text == 1) {
          return '上架';
        } else {
          return '下架';
        }
      },
    },
    {
      title: '所属菜单',
      dataIndex: 'menuName',
      key: 'menuName',
      render: function(text){
        return <span style={{color: "rgb(33, 186, 99)"}}>{text}</span>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text) => {
        if(!APP.isValidObj(text)) return "";
        return APP.momentFormatToStr(text, 'YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      title: '修改时间',
      dataIndex: 'modifytime',
      key: 'modifytime',
      render: (text) => {
        if(!APP.isValidObj(text)) return "";
        return APP.momentFormatToStr(text, 'YYYY-MM-DD HH:mm:ss');
      }
    },
  ];

  getMenuOptions = () => {
    const { menuDataSource } = this.state;
    return menuDataSource.map(item => (
      <Select.Option key={item.id} value={item.id}>
        {item.name}
      </Select.Option>
    ));
  }
}

const EditForm = Form.create()((props => {
  const { parent, form } = props;
  const { dispatch } = parent.props;
  const { loading, isShowEditModal, editData, menuDataSource } = parent.state;
  const { getFieldDecorator } = form;
  const formItemLayout = {
    style: {
      margin: '0px',
    },
  };
  //-- 显示/隐藏 数据编辑窗口
  function handlerEditModal(){
    form.resetFields();
    let { isShowEditModal, editData } = parent.state;
    isShowEditModal = !isShowEditModal;
    editData = {};
    parent.setterNewestRoleCode();
    parent.setState({ isShowEditModal, editData });
  };
  //-- 提交
  function submit(){
    form.validateFields((err, values) => {
      if(err) return;
      APP.validNilParams(values);
      request(values);
    });
    function request(params){
      APP.loading(parent);
      dispatch({
        "type": "menuButtonsModel/saveModule",
        payload: params,
        callback: function(data){
          APP.closeLoading(parent);
          if(data.success){
            message.success("保存成功！");
            parent.findPageDataSource();
            handlerEditModal();
          }else{
            message.error("编辑保存失败！");
          }
        }
      });
    }
  }
  return (
    <Modal
      title="编辑按钮"
      visible={isShowEditModal}
      width={500}
      confirmLoading={loading}
      onCancel={() => handlerEditModal()}
      onOk={() => submit()}
    >
      <Spin spinning={loading}>
        <Form>
          {getFieldDecorator('id', {
            initialValue: editData.id
          })(<Input hidden={true}/>)}
          <Form.Item label="按钮编号" {...formItemLayout}>
            {getFieldDecorator('code', {
              rules: [{ required: true, message: '请输入角色编号' }],
              initialValue: editData.code
            })(<Input placeholder="请输入角色编号"/>)}
          </Form.Item>
          <Form.Item label="按钮名称" {...formItemLayout}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入角色名称' }],
              initialValue: editData.name
            })(<Input placeholder="请输入角色名称"/>)}
          </Form.Item>
          <Form.Item label="按钮样式" {...formItemLayout}>
            {getFieldDecorator('iconCls', {
              rules: [{ required: true, message: '请输入按钮样式' }],
              initialValue: APP.changeIsNilVal(editData.iconCls, "primary")
            })(<Input placeholder="请输入按钮样式"/>)}
          </Form.Item>
          <Form.Item label="所属菜单" {...formItemLayout}>
            {getFieldDecorator('menuId', {
              rules: [{ required: true, message: '请选择菜单' }],
              initialValue: editData.menuId
            })(
              <Select placeholder={"请选择菜单"} allowClear={true}>
                {parent.getMenuOptions()}
              </Select>
            )}
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}));

export default menuButtons;
